const { CardPic, User } = require('../db');
const axios = require('axios');
const { Op, col, fn } = require('sequelize');
module.exports = {
  cardPicController(app) {
    /** 添加卡图 */
    app.post('/api/cardPic/addByCardId', async (req, res) => {
      const { cardId = '', urls = [], remark } = req.body;
      if (!cardId) {
        res.send({ code: -1, msg: '缺少参数cardId' });
        return;
      }
      const items = [];
      // console.log('🚀 ~ urls', urls);
      const _urls = !/^\{|^\[/.test(urls) ? [urls] : JSON.parse(urls.replace('\n', ''));
      // console.log('🚀 ~ _urls', _urls);
      if (_urls?.length > 0) {
        _urls.forEach((item, index) => {
          items.push({
            cardId, url: item?.url || item, remark,
          });
        });
      }
      // console.log('🚀 ~ items', items);
      // console.log('🚀 ~ CardPic', CardPic);
      const rlt = await CardPic.bulkCreate(items);
      res.send({ code: 200, data: rlt, msg: 'success' });
    });
    app.get('/api/ygo/getCardPicListByCardId', async (req, res) => {
      const { cardId = '' } = req.query;
      if (!cardId) {
        res.send({ code: -1, msg: '缺少参数cardId' });
        return;
      }
      const rlt = (await CardPic.findAll({
        where: { cardId, isDelete: 0 },
        order: [
          ['isDoujin', 'ASC'],
          ['tag', 'ASC'],
        ],
      }))?.map(_ => _.dataValues);
      res.send({ code: 200, data: rlt, msg: 'success' });
    });
    // 根据url添加卡
    app.post('/api/cardPic/addBySyUrl', async (req, res) => {
      const { urls = [], isSy = true, tag } = req.body;
      const items = [];
      const _urls = !/^\{|^\[/.test(urls) ? [urls] : JSON.parse(urls.replace('\n', ''));
      console.log('🚀 ~ _urls', _urls);
      if (_urls?.length > 0) {
        for (let i = 0; i < _urls?.length; i++) {
          // demo: https://file.wygsy.com/tct/1648264233363234857/wygtech-storage-platform/1626145487579757314/20241125/雷击-备注_1732528068387.png
          const url = typeof _urls[i] === 'string' ? _urls[i] : _urls[i]?.url;
          const paths = url.split('/');
          const fileName = paths[paths.length - 1];
          const monsterNameAndRemark = isSy ? fileName.split('_')[fileName.split('_').length - 2] : fileName.split('.')[fileName.split('.').length - 2];
          // console.log('🚀 ~ monsterNameAndRemark', monsterNameAndRemark);
          // const [monsterName, remark = ''] = monsterNameAndRemark.split('-');
          const monsterNameAndRemarkArr = monsterNameAndRemark.split('~');
          const remark = monsterNameAndRemarkArr?.length > 1 ? monsterNameAndRemarkArr?.[monsterNameAndRemarkArr.length - 1] : '';
          const monsterName = monsterNameAndRemark.replace(`~${ remark }`, '');
          const searchRes = await axios.get(`https://ygocdb.com/api/v0/?search=${ monsterName }`);
          // console.log('🚀 ~ searchRes.data', searchRes.data);
          const rlt = searchRes.data.result?.[0];
          let _tag = (tag || remark)?.trim();
          const isDoujin = /^同人-/.test(_tag);
          _tag = _tag.replace('同人-', '');
          if (rlt) {
            const { id } = rlt;
            items.push({
              cardId: id, url: url, remark: `${ rlt.cn_name }`, tag: _tag,
              isDoujin,
            });
          } else {
            console.log(`🚀 ~ 找不到：${ monsterName }`);
          }
        }
      }
      console.log('🚀 ~ items', items);
      const rlt = await CardPic.bulkCreate(items);
      res.send({ code: 200, data: rlt, msg: 'success' });
      // res.send({ code: 200, data: true, msg: 'success' });
    });
    // 批量查询异画数量ByID，ID用逗号分隔
    app.post('/api/cardPic/batchQueryPicCountByIds', async (req, res) => {
      const { ids = '' } = req.body;
      const _ids = ids?.split(',').map(_ => _.trim());
      if (!_ids?.length) {
        res.send({ code: -1, msg: '缺少参数ids' });
        return;
      }
      try {
        const whereIds = _ids.map(_ => ({ cardId: _ }));
        const rlt = await CardPic.findAll({
          attributes: [[col('cardId'), 'cardId'], [fn('COUNT', col('*')), 'count']],
          where: {
            [Op.or]: whereIds,
          },
          group: ['cardId'],
        });
        // console.log('🚀 ~ rlt', rlt);
        res.send({ code: 200, data: rlt, msg: 'success' });
      } catch (e) {
        res.send({ code: -1, msg: `${ e.message }` });
      }
    });
  },
};
